package application.mvc.sys.config.base;

import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;

import com.jfinal.kit.StrKit;

import application.common.model.Config;
import application.common.render.Option;
import application.common.util.LayerUtil;
import application.common.util.PwdUtil;
import application.common.util.RouteUtil;
import application.common.util.ShiroUtil;
import javafx.animation.Animation;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.RotateTransition;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.util.Duration;
import javafx.util.StringConverter;

public class BaseConfigController implements Initializable{

	
	@FXML
	private Label headerLabel;
	
	@FXML
	private Label copyrightLabel;
	
	@FXML
	private Label usernameLabel;
	
	@FXML
	private Label roleNameLabel;
	
	@FXML
	private ImageView portraitImageView;
	
	@FXML
	private TextField idTextField;
	@FXML
	private TextField nameTextField;
	@FXML
	private TextField phoneTextField;
	@FXML
	private TextArea copyrightTextArea;
	@FXML
	private RadioButton isVideotapeRBtnTrue;
	@FXML
	private RadioButton isVideotapeRBtnFalse;
	@FXML
	private TextField videotapePathTextField;
	
	@FXML
	private PasswordField passwordField;
	
	@FXML
	private PasswordField againPasswordField;
	
	@FXML
	private TextField picturePathTextField;
	
	@FXML
	private RadioButton devModeRBtnTrue;
	@FXML
	private RadioButton devModeRBtnFalse;
	@FXML
	private TextField cabinetTimeoutTextField;
	@FXML
	private TextField synURLTextField;
	@FXML
	private TextField synFrequencyTextField;
	@FXML
	private TextField timeoutTextField;
	@FXML
	private TextField scannerSerialPortTextField;
	@FXML
	private ChoiceBox<Option> scannerModelChoiceBox;
	
	@FXML
	private TextField softMainNameTextField;
	@FXML
	private TextField softPathTextField;
	@FXML
	private TextField softBackPathTextField;
	@FXML
	private TextField updateSoftTextField;
	
	
	@FXML
	private Pane timerOutLinePane;

	@FXML
	private Pane timerInLinePane;

	@FXML
	private Label timerLabel;
	private Timeline animation;
	private RotateTransition rotateTransitionOut;
	private RotateTransition rotateTransitionIn;
	
	private boolean isDestroy=false;
	
	public void initialize(URL location, ResourceBundle resources) {
		
		headerLabel.setText(ShiroUtil.getSoftName());
		copyrightLabel.setText(ShiroUtil.getCopyright());
		
		if(ShiroUtil.getUser()!=null) {
			portraitImageView.setImage(ShiroUtil.getUser().getPortrait());
			usernameLabel.setText(ShiroUtil.getUser().getName());
			roleNameLabel.setText(ShiroUtil.getUser().getRoleName());
		}
		
		
		ToggleGroup isVideotapeGroup = new ToggleGroup();
		ToggleGroup devModeGroup = new ToggleGroup();

		isVideotapeRBtnTrue.setToggleGroup(isVideotapeGroup);
		isVideotapeRBtnFalse.setToggleGroup(isVideotapeGroup);
		isVideotapeRBtnTrue.setUserData("1");
		isVideotapeRBtnFalse.setUserData("0");
		
		
		devModeRBtnTrue.setToggleGroup(devModeGroup);
		devModeRBtnFalse.setToggleGroup(devModeGroup);
		devModeRBtnTrue.setUserData("true");
		devModeRBtnFalse.setUserData("false");
		
		
		
		
		scannerModelChoiceBox.getItems().addAll(
			new Option("1","斯普锐 SE2102"),
			new Option("2","MOTOSE3307"),
			new Option("3","民德 ES46XX"),
			new Option("4"," ZT661/FM420/FM430/EM2037/EM2039"),
			new Option("5","北京微光二维码"),
			new Option("6","FR20/FM30"),
			new Option("7","霍尼韦尔 N3680"),
			new Option("8","意锐 RE6110"),
			new Option("9","斯普锐 SE7130C")
		);
		
		scannerModelChoiceBox.setConverter(new StringConverter<Option>() {
			@Override
			public String toString(Option object) {
				return object.getLabel();
			}
			
			@Override
			public Option fromString(String string) {
				return null;
			}
		});
		
		if(ShiroUtil.getUser()!=null) {
			portraitImageView.setImage(ShiroUtil.getUser().getPortrait());
		}
		
		Config config=ShiroUtil.getConfig();
		
		idTextField.setText(config!=null?config.getId():"");
		nameTextField.setText(config!=null?config.getName():"智能卷宗柜");
		phoneTextField.setText(config!=null?config.getPhone():"");
		copyrightTextArea.setText(config!=null?config.getCopyright():"");
		
		if(config==null || StrKit.equals(config.getIsVideotape(),"0")) {
			isVideotapeRBtnFalse.setSelected(true);
		}else {
			isVideotapeRBtnFalse.setSelected(false);
		}
		
		videotapePathTextField.setText(config!=null?config.getVideotapePath():"");
		synURLTextField.setText(config!=null?config.getSynURL():"");
		synFrequencyTextField.setText(config!=null?config.getSynFrequency():"60");
		timeoutTextField.setText(config!=null?config.getTimeout():"60");
		scannerSerialPortTextField.setText(config!=null?config.getScannerSerialPort():"COM11:9600:E:8:1");
		picturePathTextField.setText(config!=null?config.getPicturePath():"");
		cabinetTimeoutTextField.setText(config!=null?config.getCabinetTimeout()+"":"20");
		
		softMainNameTextField.setText(config!=null && !StrKit.isBlank(config.getSoftMainName())?config.getSoftMainName()+"":"main.jar");
		softPathTextField.setText(config!=null && !StrKit.isBlank(config.getSoftPath())?config.getSoftPath()+"":"");
		softBackPathTextField.setText(config!=null && !StrKit.isBlank(config.getSoftBackPath())?config.getSoftBackPath()+"":"");
		updateSoftTextField.setText(config!=null && !StrKit.isBlank(config.getUpdateSoft())?config.getUpdateSoft()+"":"");
		
		
		
		if(config!=null && StrKit.equals("1",config.getDevMode())) {
			devModeRBtnTrue.setSelected(true);
		}else {
			devModeRBtnFalse.setSelected(false);
		}
		
		scannerModelChoiceBox.getSelectionModel().selectFirst();//默认选中第一个选项
		if(config!=null) {
			try {
				scannerModelChoiceBox.getSelectionModel().select(Integer.parseInt(config.getScannerModel())-1);
			}catch (Exception e) {
				scannerModelChoiceBox.getSelectionModel().select(8);
			}
		}
		
		if(!isDestroy) {
			rotateTransitionOut = new RotateTransition(Duration.seconds(10), timerOutLinePane);
			rotateTransitionOut.setFromAngle(0);
			rotateTransitionOut.setToAngle(360);
			rotateTransitionOut.setByAngle(360); // 设置旋转的角度
			rotateTransitionOut.setCycleCount(Animation.INDEFINITE); // 设置旋转次数，我们需要旋转无数次
			rotateTransitionOut.setInterpolator(Interpolator.LINEAR);
			rotateTransitionOut.play();

			rotateTransitionIn = new RotateTransition(Duration.seconds(10), timerInLinePane);
			rotateTransitionIn.setFromAngle(360);
			rotateTransitionIn.setToAngle(0);
			rotateTransitionIn.setByAngle(360); // 设置旋转的角度
			rotateTransitionIn.setCycleCount(Animation.INDEFINITE); // 设置旋转次数，我们需要旋转无数次
			rotateTransitionIn.setInterpolator(Interpolator.LINEAR);
			rotateTransitionIn.play();
			startCountDown();
		}
	}
	
	public void startCountDown() {
		animation = new Timeline(new KeyFrame(Duration.millis(1000), new EventHandler<ActionEvent>() {
			public void handle(ActionEvent event) {
				if(RouteUtil.getTime()>0) {
					RouteUtil.setTime(RouteUtil.getTime() - 1);
					if (RouteUtil.getTime() == 0) {
						timerLabel.setText("0");
						LayerUtil.open("操作超时！", 999);
					} else if (RouteUtil.getTime() > 0) {
						timerLabel.setText(RouteUtil.getTime() + "");
					}
				}
				
			}
		}));
		animation.setCycleCount(Timeline.INDEFINITE);
		animation.play();
	}

	public void destroy() {
		if (animation != null) {
			animation.stop();
		}
		if (rotateTransitionOut != null) {
			rotateTransitionOut.stop();
		}
		if (rotateTransitionIn != null) {
			rotateTransitionIn.stop();
		}
	}
	
	public void exit(ActionEvent event) {
		if(!isDestroy) {
			isDestroy=true;
			Button bu = (Button) event.getSource();
			bu.setVisible(false);
			destroy();
			RouteUtil.goConfig();
		}
	}
	
	public void directoryChooser(ActionEvent event) {
        final DirectoryChooser directoryChooser = new DirectoryChooser();
        File file = directoryChooser.showDialog(RouteUtil.mainStage);
        if (file != null) {
        	videotapePathTextField.setText(file.getPath());
        }
	}
	
	public void picDirectoryChooser(ActionEvent event) {
        final DirectoryChooser directoryChooser = new DirectoryChooser();
        File file = directoryChooser.showDialog(RouteUtil.mainStage);
        if (file != null) {
        	picturePathTextField.setText(file.getPath());
        }
	}
	
	public void softPathChooser(ActionEvent event) {
        final DirectoryChooser directoryChooser = new DirectoryChooser();
        File file = directoryChooser.showDialog(RouteUtil.mainStage);
        if (file != null) {
        	softPathTextField.setText(file.getPath());
        }
	}
	
	public void softBackPathChooser(ActionEvent event) {
        final DirectoryChooser directoryChooser = new DirectoryChooser();
        File file = directoryChooser.showDialog(RouteUtil.mainStage);
        if (file != null) {
        	softBackPathTextField.setText(file.getPath());
        }
	}
	
	public void updateSoftChooser(ActionEvent event) {
        final FileChooser fileChooser = new FileChooser();
        File file = fileChooser.showOpenDialog(RouteUtil.mainStage);
        if (file != null) {
        	updateSoftTextField.setText(file.getPath());
        }
	}
	
	public void next(ActionEvent event) {
		if(!isDestroy) {
			isDestroy=true;
			Button bu = (Button) event.getSource();
			bu.setVisible(false);
			String id =idTextField.getText();
			if(StrKit.isBlank(id)) {
				LayerUtil.open("授权不可以空！", 500);
				bu.setVisible(true);
				isDestroy=false;
				return;
			}
			Config config=Config.dao.findById(id);
			if(config==null) {
				config=new Config();
			}
			config.setName(nameTextField.getText());
			config.setPhone(phoneTextField.getText());
			config.setCopyright(copyrightTextArea.getText());
			config.setVideotapePath(videotapePathTextField.getText());
			config.setSynURL(synURLTextField.getText());
			config.setSynFrequency(synFrequencyTextField.getText());
			config.setTimeout(timeoutTextField.getText());
			config.setScannerModel(scannerModelChoiceBox.getSelectionModel().getSelectedItem().getValue());
			config.setScannerSerialPort(scannerSerialPortTextField.getText());
			config.setPicturePath(picturePathTextField.getText());
			
			config.setSoftMainName(softMainNameTextField.getText());
			config.setSoftPath(softPathTextField.getText());
			config.setSoftBackPath(softBackPathTextField.getText());
			config.setUpdateSoft(updateSoftTextField.getText());
			
			try {
				config.setCabinetTimeout(Integer.parseInt(cabinetTimeoutTextField.getText()));
			}catch (Exception e) {
				config.setCabinetTimeout(20);
			}
		
			if(devModeRBtnTrue.isSelected()) {
				config.setDevMode("1");
			}else {
				config.setDevMode("0");
			}
			
			if(!StrKit.isBlank(passwordField.getText())) {
				if(!StrKit.equals(passwordField.getText(),againPasswordField.getText())) {
					LayerUtil.open("两次输入密码不一致！", 200);
					bu.setVisible(true);
					isDestroy=false;
					return;
				}
				config.setPassword(PwdUtil.encrypt(passwordField.getText()));
			}
			
			if(isVideotapeRBtnTrue.isSelected()) {
				config.setIsVideotape("1");
			}else {
				config.setIsVideotape("0");
			}
			
			try {
				if(StrKit.isBlank(config.getId())) {
					config.setId(id);
					if(config.save()) {
						ShiroUtil.setConfig(config);
						LayerUtil.open("保存配置成功！", 200);
					}else {
						LayerUtil.open("保存配置失败！", 500);
					}
				}
				else {
					if(config.update()) {
						ShiroUtil.setConfig(config);
						LayerUtil.open("更新配置成功！", 200);
					}else {
						LayerUtil.open("更新配置失败！", 500);
					}
				}
			}catch (Exception e) {
				LayerUtil.open("系统异常！", 500);
			}
			bu.setVisible(true);
			isDestroy=false;
		}
	}

}
